package br.com.usapre.faces;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 * @version 1.0.0
 * @since Janeiro,29 2013
 * @author Eduardo Francisco Barbosa
 */
public class OperacoesArquivos {

    /**
     * downloadFile
     * 
     * @param File
     *            file
     * @param String
     *            mimeType
     * @param FacesContext
     *            facesContext
     */
    public static synchronized void downloadFile(File file, String mimeType, FacesContext facesContext) {

	ExternalContext context = facesContext.getExternalContext(); // Context

	context.responseReset();

	// HttpServletResponse response = (HttpServletResponse)
	// context.getResponse();
	context.setResponseHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
	context.setResponseContentLength((int) file.length());
	context.setResponseContentType(mimeType);

	try {
	    FileInputStream in = new FileInputStream(file);
	    OutputStream out = context.getResponseOutputStream();

	    byte[] buf = new byte[(int) file.length()];
	    int count;
	    while ((count = in.read(buf)) >= 0) {
		out.write(buf, 0, count);
	    }
	    in.close();
	    out.flush();
	    out.close();
	    facesContext.responseComplete();
	} catch (IOException ex) {
	    System.out.println("Erro no downloadFile: " + ex.getMessage());
	    ex.printStackTrace();
	}
    }

}
